const dbHelper = require('../dbhelper/device')
const tool = require('../util/tool');
const ApiError = require('../error/api_error');
const ApiErrorNames = require('../error/api_error_name');
const Model = require('../models/device')
const fs = require("fs");
/**
 * 查
 */
exports.find = async (ctx) => {
  let result;
  const reqQuery = ctx.query;
  //get查询中的带query
  if (reqQuery && !tool.isEmptyObject(reqQuery)) {
    if (reqQuery.id) {
      result = dbHelper.finById(reqQuery.id);
    } else {
      //console.log('检查到是get?没有Id')
      result = dbHelper.findSome(reqQuery)
    }
  } else {
    result = dbHelper.findAll();//不带就返回所有
  }

  await result.then((res) => {
    if (res) {
      ctx.body = res;
    } else {
      throw new ApiError(ApiErrorNames.UNEXIST_ID);
    }
  }).catch((err) => {
    throw new ApiError(err.name, err.message);
  });

};

//restfull风格查动态路由id
exports.detail = async (ctx) => {
  const {id} = ctx.params;
  if (!tool.validatorsFun.numberAndCharacter(id)) {
    throw new ApiError(ApiErrorNames.LEGAL_ID);
  }
  await dbHelper.finById(id).then((res) => {
    if (res) {
      ctx.body = res;
    } else {
      throw new ApiError(ApiErrorNames.UNEXIST_ID);
    }
  }).catch((err) => {
    if (err.name === 'CastError') {
      throw new ApiError(ApiErrorNames.UNEXIST_ID);
    } else {
      throw new ApiError(err.name, err.message);
    }

  });
};

exports.add = async (ctx) => {
  const dataObj = ctx.request.body;
  await dbHelper.add(dataObj).then((res) => {
    ctx.body = res;
  }).catch((err) => {
    throw new ApiError(err.name, err.message);
  });
};

exports.fileAdd = async (ctx) => {
  const {id} = ctx.params;
  const dataObj = ctx.request.body;
  if (!tool.validatorsFun.numberAndCharacter(id)) {
    throw new ApiError(ApiErrorNames.LEGAL_ID);
  }
  // 创建可写流
  //const stream = fs.createWriteStream(ctx.request.files.file.path);
  const stream = fs.readFileSync(ctx.request.files.file.path)
  dataObj.file = stream
 //await Model.findOneAndUpdate({_id: id}, {$push: {files: dataObj},}, {new: true}).select({files: {file: 0}}).exec().then(
  await Model.findOneAndUpdate({_id: id}, {$push: {files: dataObj},}, {new: true}).exec().then(
    res => {
      if (res) {
        ctx.body = res;
      } else {
        throw new ApiError(ApiErrorNames.UNEXIST_ID);
      }
    }
  ).catch((err) => {
    throw new ApiError(err.name, err.message);
  });
},
  exports.fileDetail = async (ctx) => {
    const {id, f_id} = ctx.params;
    const dataObj = ctx.request.body;
    if (!tool.validatorsFun.numberAndCharacter(id)) {
      throw new ApiError(ApiErrorNames.LEGAL_ID);
    }

    await Model.findOne({_id: id, 'files._id': f_id},).exec().then(
      res => {
        if (res) {
          for (let index in res.files) {
            if (res.files[index]['_id'] == f_id) {
              ctx.body = res.files[index]
            }
          }
        } else {
          throw new ApiError(ApiErrorNames.UNEXIST_ID);
        }
      }
    ).catch((err) => {
      throw new ApiError(err.name, err.message);
    });
  },
  /**
   * 更新
   */
  exports.update = async (ctx) => {
    const ctxParams = ctx.params;
    // 合并 路由中的参数 以及 发送过来的参数
    // 路由参数 以及发送的参数可能都有 id 以 发送的 id 为准，如果没有，取路由中的 id
    const dataObj = {...ctxParams, ...ctx.request.body};

    await dbHelper.update(dataObj).then((res) => {
      if (res) {
        ctx.body = res;
      } else {
        throw new ApiError(ApiErrorNames.UNEXIST_ID);
      }
    }).catch((err) => {
      throw new ApiError(err.name, err.message);
    });
  };

/**
 * 删除
 */
exports.delete = async (ctx) => {
  const ctxParams = ctx.params;
  // 合并 路由中的参数 以及 发送过来的参数
  // 路由参数 以及发送的参数可能都有 id 以 发送的 id 为准，如果没有，取路由中的 id
  const dataObj = {...ctxParams, ...ctx.request.body};
  if (!tool.validatorsFun.numberAndCharacter(dataObj.id)) {
    throw new ApiError(ApiErrorNames.LEGAL_ID);
  }

  await dbHelper.delete(dataObj.id).then((res) => {
    if (res) {
      ctx.body = res;
    } else {
      throw new ApiError(ApiErrorNames.UNEXIST_ID);
    }
  }).catch((err) => {
    throw new ApiError(err.name, err.message);
  });
};

exports.fileDelete = async (ctx) => {
  const {id, f_id} = ctx.params;
  if (!tool.validatorsFun.numberAndCharacter(id) || !tool.validatorsFun.numberAndCharacter(f_id)) {
    throw new ApiError(ApiErrorNames.LEGAL_ID);
  }
 // await Model.findOneAndUpdate({_id: id}, {$pull: {files: {_id: f_id}}}, {}).select({files: {file: 0}}).exec().then(
  await Model.findOneAndUpdate({_id: id}, {$pull: {files: {_id: f_id}}}, {}).exec().then(
    res => {
      if (res) {
        if (res && res.files.length > 0) {
          for (let index in res.files) {
            if (res.files[index]._id == f_id) {
             // res.files.remove( res.files[index])
              res.files.splice(index,1)
            }
          }
          ctx.body = res;
        } else {
          throw new ApiError(ApiErrorNames.UNEXIST_ID);
        }
      }
    }
  ).catch((err) => {
    throw new ApiError(err.name, err.message);
  });
}



